#include "DHT11.h"
#include "bflb_gpio.h"
#include "bflb_mtimer.h"
#include "log.h"

struct bflb_device_s *gpio;

void init_GPIO()
{
    // 初始化GPIO引脚
    gpio = bflb_device_get_by_name("gpio");
    LCD_Init(); // LCD初始化
    LCD_Fill(0, 0, LCD_W, LCD_H, WHITE);
}

void DHT_START()
{
    // 初始化GPIO
    bflb_gpio_init(gpio, DHT_PIN, GPIO_OUTPUT | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_1);

    // 发送开始信号
    bflb_gpio_set(gpio, DHT_PIN);
    bflb_mtimer_delay_ms(50);
    bflb_gpio_reset(gpio, DHT_PIN);
    bflb_mtimer_delay_ms(20);
    bflb_gpio_set(gpio, DHT_PIN);
    bflb_mtimer_delay_us(30);

    // 切换为输入模式并等待DHT11的响应
    bflb_gpio_init(gpio, DHT_PIN, GPIO_INPUT | GPIO_PULLUP | GPIO_SMT_EN);

    // 读取DHT11的响应
    while (bflb_gpio_read(gpio, DHT_PIN) == 1)
    {
    }
    while (bflb_gpio_read(gpio, DHT_PIN) == 0)
    {
    }
    while (bflb_gpio_read(gpio, DHT_PIN) == 1)
    {
    }

    // 读取温湿度数据 共 40bits
    // 8bit湿度整数数据+8bit湿度小数数据
    // +8bi温度整数数据+8bit温度小数数据
    // +8bit校验和

    uint8_t data[5] = {0};
    for (int i = 0; i < 5; i++)
    {
        data[i] = 0;
        for (int j = 0; j < 8; j++)
        {
            while (bflb_gpio_read(gpio, DHT_PIN) == 0)
            {
            }
            bflb_mtimer_delay_us(30);
            if (bflb_gpio_read(gpio, DHT_PIN) == 1)
            {
                data[i] |= (1 << (7 - j));
                while (bflb_gpio_read(gpio, DHT_PIN) == 1)
                {
                }
            }
        }
    }

    // // 关闭GPIO
    // bflb_gpio_deinit(gpio, DHT_PIN);

    // 解析数据
    uint8_t humidity_integer = data[0];
    uint8_t humidity_decimal = data[1];
    uint8_t temperature_integer = data[2];
    uint8_t temperature_decimal = data[3];

    // 计算小数部分
    float humidity = humidity_integer + (humidity_decimal / 10.0);
    float temperature = temperature_integer + (temperature_decimal / 10.0);

    LCD_ShowString(1, 50, "Temperature:", BLACK, WHITE, 12, 1);
    LCD_ShowFloatNum1(73, 48, temperature, 4, RED, WHITE, 16);
    LCD_ShowString(1, 80, "Humidity:", BLACK, WHITE, 12, 1);
    LCD_ShowFloatNum1(73, 78, humidity, 4, RED, WHITE, 16);
}
